import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { creditsService, UserCredits, CreditPackage, CREDIT_PACKAGES } from '../services/credits';
import { getUserDesigns, Design } from '../services/design';
import CreditPackageGrid from './CreditPackageGrid';
import StripePayment from './StripePayment';

interface BillingManagementProps {
  userCredits: UserCredits | null;
}

const BillingManagement: React.FC<BillingManagementProps> = ({ userCredits }) => {
  const [designs, setDesigns] = useState<Design[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null);
  
  const { user, isAuthenticated } = useAuth();
  const history = useHistory();

  // 使用预定义的积分包
  const quickRechargePackages: CreditPackage[] = CREDIT_PACKAGES;

  // 处理购买
  const handleQuickPurchase = (creditPackage: CreditPackage) => {
    // 检查用户是否登录
    if (!isAuthenticated || !user) {
      setError('Please login first to purchase credits');
      setTimeout(() => {
        history.push('/login');
      }, 3000);
      return;
    }

    // 显示支付弹窗
    setSelectedPackage(creditPackage);
    setShowPaymentModal(true);
    setError('');
    setSuccess('');
  };
  
  // 处理支付成功
  const handlePaymentSuccess = async (paymentIntent: any) => {
    if (!selectedPackage || !user) return;

    setIsLoading(true);
    setShowPaymentModal(false);

    try {
      // 调用后端API处理支付成功
      const updatedCredits = await creditsService.handlePaymentSuccess(
        user.id,
        selectedPackage.id,
        paymentIntent.id
      );
      
      // 更新用户积分信息 - 这里需要通过props传递或其他方式更新父组件的userCredits
      setSuccess(`Successfully purchased ${selectedPackage.credits} credits! Your new balance is ${updatedCredits.creditBalance} credits.`);
      
      // 清除成功消息
      setTimeout(() => {
        setSuccess('');
      }, 10000);
    } catch (error: any) {
      setError(error.message || 'Failed to process payment. Please contact support if credits were charged.');
    } finally {
      setIsLoading(false);
      setSelectedPackage(null);
    }
  };

  // 处理支付错误
  const handlePaymentError = (errorMessage: string) => {
    setError(errorMessage);
    setShowPaymentModal(false);
    setSelectedPackage(null);
    
    setTimeout(() => {
      setError('');
    }, 5000);
  };

  // 处理支付取消
  const handlePaymentCancel = () => {
    setShowPaymentModal(false);
    setSelectedPackage(null);
  };
  
  const loadDesigns = async () => {
    if (!user) return;
    
    setLoading(true);
    try {
      const response = await getUserDesigns();
      setDesigns(response.data?.designs || []);
    } catch (error: any) {
      console.error('Failed to load designs:', error);
      setDesigns([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (user) {
      loadDesigns();
    }
  }, [user]);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 md:p-8">
        <h2 className="text-2xl font-bold text-gray-900 mb-6">Billing Management</h2>
        
        {/* 账户概览 */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-6 mb-8">
          <div className="bg-gradient-to-r from-indigo-500 to-indigo-600 rounded-lg p-6 text-white">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-indigo-100 text-sm">Current Balance</p>
                <p className="text-3xl font-bold">{userCredits?.creditBalance || 0}</p>
                <p className="text-indigo-200 text-xs mt-1">Credits</p>
              </div>
              <svg className="w-8 h-8 text-indigo-200" fill="currentColor" viewBox="0 0 20 20">
                <path d="M4 4a2 2 0 00-2 2v1h16V6a2 2 0 00-2-2H4z"/>
                <path fillRule="evenodd" d="M18 9H2v5a2 2 0 002 2h12a2 2 0 002-2V9zM4 13a1 1 0 011-1h1a1 1 0 110 2H5a1 1 0 01-1-1zm5-1a1 1 0 100 2h1a1 1 0 100-2H9z" clipRule="evenodd"/>
              </svg>
            </div>
          </div>
          
          <div className="bg-gradient-to-r from-emerald-500 to-emerald-600 rounded-lg p-6 text-white">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-emerald-100 text-sm">Days remaining</p>
                <p className="text-3xl font-bold">{userCredits?.daysUntilExpiration || '∞'}</p>
                <p className="text-emerald-200 text-xs mt-1">Days</p>
              </div>
              <svg className="w-8 h-8 text-emerald-200" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M10 2a4 4 0 00-4 4v1H5a1 1 0 00-.994.89l-1 9A1 1 0 004 18h12a1 1 0 00.994-1.11l-1-9A1 1 0 0015 7h-1V6a4 4 0 00-4-4zm2 5V6a2 2 0 10-4 0v1h4zm-6 3a1 1 0 112 0 1 1 0 01-2 0zm7-1a1 1 0 100 2 1 1 0 000-2z" clipRule="evenodd"/>
              </svg>
            </div>
          </div>
          
          <div className="bg-gradient-to-r from-rose-500 to-rose-600 rounded-lg p-6 text-white">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-rose-100 text-sm">Status</p>
                <p className="text-3xl font-bold">{userCredits?.isExpired ? 'Expired' : 'Active'}</p>
                <p className="text-rose-200 text-xs mt-1">Credit Status</p>
              </div>
              <svg className="w-8 h-8 text-rose-200" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clipRule="evenodd"/>
              </svg>
            </div>
          </div>
        </div>
        
        {/* 全局消息显示 */}
        {error && (
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="mb-6 bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-lg"
            role="alert"
          >
            <span className="block sm:inline">{error}</span>
          </motion.div>
        )}

        {success && (
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="mb-6 bg-green-50 border border-green-200 text-green-600 px-4 py-3 rounded-lg"
            role="alert"
          >
            <span className="block sm:inline">{success}</span>
          </motion.div>
        )}
        
        {/* Quick Recharge */}
        <div className="mb-8">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Quick Recharge</h3>
          <CreditPackageGrid
            creditPackages={quickRechargePackages}
            isLoading={isLoading}
            isAuthenticated={isAuthenticated || false}
            onPurchase={handleQuickPurchase}
            defaultHighlightIndex={1}
          />
          <div className="mt-4">
            <button
              onClick={() => history.push('/buy-credits')}
              className="w-full sm:w-auto px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
            >
              Custom Recharge Amount
            </button>
          </div>
        </div>
        
        {/* Consumption Records */}
        <div>
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Recent Consumption Records</h3>
          {loading ? (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
              <p className="text-gray-600">Loading consumption records...</p>
            </div>
          ) : (
            <div className="space-y-3">
              {Array.isArray(designs) && designs.filter(d => d.creditsUsed > 0).slice(0, 10).map((design) => (
                <div key={design.id} className="flex flex-col sm:flex-row sm:items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div className="flex items-center space-x-3 mb-2 sm:mb-0">
                    <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0">
                      <svg className="w-5 h-5 text-red-600" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M10 2a4 4 0 00-4 4v1H5a1 1 0 00-.994.89l-1 9A1 1 0 004 18h12a1 1 0 00.994-1.11l-1-9A1 1 0 0015 7h-1V6a4 4 0 00-4-4zm2 5V6a2 2 0 10-4 0v1h4zm-6 3a1 1 0 112 0 1 1 0 01-2 0zm7-1a1 1 0 100 2 1 1 0 000-2z" clipRule="evenodd"/>
                      </svg>
                    </div>
                    <div>
                      <p className="font-medium text-gray-900">Design Generation - {design.roomType}</p>
                      <p className="text-sm text-gray-500">{formatDate(design.createdAt)}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="font-semibold text-red-600">-{design.creditsUsed} Credits</p>
                    <p className="text-sm text-gray-500">{design.designStyle}</p>
                  </div>
                </div>
              ))}
            </div>
          )}
          
          {(!Array.isArray(designs) || designs.filter(d => d.creditsUsed > 0).length === 0) && !loading && (
            <div className="text-center py-8">
              <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
              </svg>
              <h3 className="mt-2 text-sm font-medium text-gray-900">No Consumption Records</h3>
              <p className="mt-1 text-sm text-gray-500">You don't have any consumption records yet</p>
            </div>
          )}
        </div>
      </div>
      
      {/* 支付弹窗 */}
      {showPaymentModal && selectedPackage && user && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-white rounded-xl shadow-xl max-w-md w-full max-h-[90vh] overflow-y-auto"
          >
            <div className="p-6">
              <div className="flex justify-between items-center mb-6">
                <h3 className="text-xl font-bold text-gray-900">
                  Purchase {selectedPackage.name}
                </h3>
                <button
                  onClick={handlePaymentCancel}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              <StripePayment
                creditPackage={selectedPackage}
                userId={user.id.toString()}
                onSuccess={handlePaymentSuccess}
                onError={handlePaymentError}
                onCancel={handlePaymentCancel}
              />
            </div>
          </motion.div>
        </div>
      )}

      {/* 加载遮罩 */}
      {isLoading && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 flex items-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mr-3"></div>
            <span className="text-gray-700">Processing your purchase...</span>
          </div>
        </div>
      )}
    </motion.div>
  );
};

export default BillingManagement;